package com.mego.tzadd.activitys;


import android.annotation.SuppressLint;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.SystemClock;
import android.util.Log;

import com.mego.tzadd.database.dbmodel.SystemAllInfo;
import com.mego.tzadd.database.manager.SystemCenter;
import com.mego.tzadd.utils.AlarmReceiver;

/**
 * This Service is Persistent Service. Do some what you want to do here.<br/>
 * <p>
 * Created by Mars on 12/24/15.
 */
public class Service3 extends Service {

    //测试的service-- 进程关闭了，这个也就没有了
    int _num = 0;

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @SuppressLint("WrongConstant")
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        //onStartCommand -- startService(intentOne); 每次都进

        AlarmManager manager = (AlarmManager) getSystemService(ALARM_SERVICE);
        int anHour = 1000; //1秒
        long triggerAtTime = SystemClock.elapsedRealtime() + anHour;
        Intent i = new Intent(this, AlarmReceiver.class);
        PendingIntent pi = PendingIntent.getBroadcast(this, 0, i, 0);
        manager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtTime, pi);

        //数据库无法写入
        SystemCenter.getInstance().saveSysInfo(new SystemAllInfo(null, "mmm", "kkk"));

        String mobile = "";
        SystemAllInfo infoname = SystemCenter.getInstance().getSysInfo("mmm");
        if (infoname != null) {
            mobile = infoname.getContent();
        }

        _num++;
        Log.d("MainService", "Service3--onStartCommand--" + _num + " " + mobile);

        return Service.START_FLAG_REDELIVERY;

    }
}

// 结论
// 1. 单独启动service， app正常退出后service可以保持运行；但清理后台，service也还是会被关闭；
// 2. service里数据库写入读取都不行，
//        Intent i3 = new Intent(this, Service3.class);
//        i3.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//        startService(i3);